# Create your views here.

from django.http import HttpResponse
from django import forms
from django.template import Template, Context
from django.shortcuts import render_to_response
from myapp.models import *
from django.views.decorators.csrf import *


#-------------- Function From Natsuda Srikhlai -----------------#
class ContactForm(forms.Form): #Form add student
	sID = forms.CharField(max_length=10, label='Student ID')
	sName = forms.CharField(max_length=30, label='Name')
	sLastname = forms.CharField(max_length=30, label='Lastname')
	secID = forms.IntegerField(label='Section')
	lab1 = forms.IntegerField(label='Score Lab1')
	lab2 = forms.IntegerField(label='Score Lab2')
	lab3 = forms.IntegerField(label='Score Lab3')
	lab4 = forms.IntegerField(label='Score Lab4')
	Midterm1 = forms.IntegerField(label='Score Midterm1')
	Midterm2 = forms.IntegerField(label='Score Midterm2')
	Midterm3 = forms.IntegerField(label='Score Midterm3')
	Midterm4 = forms.IntegerField(label='Score Midterm4')
	Final1 = forms.IntegerField(label='Score Final1')
	Final2 = forms.IntegerField(label='Score Final2')
	Final3 = forms.IntegerField(label='Score Final3')
	Final4 = forms.IntegerField(label='Score Final4')

class ContactFormCourse(forms.Form): #Form add course
	SubjectID = forms.CharField(max_length=10, label='Subject ID')
	SubjectName = forms.CharField(max_length=30,label='Subject Name')
	SectionID = forms.IntegerField(label='Section ID')
	ListTA = forms.CharField(label='TA Name')
	ListTeacher = forms.CharField(label='Teacher Name')

class ContactFormLogin(forms.Form): #Form Login
	Username = forms.CharField(max_length=10, label='Username')
	passwords = forms.CharField(widget=forms.PasswordInput, max_length=20, label='Password')

class ContactFormChangePassword(forms.Form): #Form change password
	CurrentPassword = forms.CharField(widget=forms.PasswordInput, max_length=20, label='Current Password')
	NewPassword = forms.CharField(widget=forms.PasswordInput, max_length=20, label='New Password')
	NewPassword2 = forms.CharField(widget=forms.PasswordInput, max_length=20, label='New Password (again)')



def Show_Course(request): # Show Detial of course
	if "role" in request.session: #Check role in session
		course_list = Course.objects.all()
		return render_to_response('showcourse.html',locals())
	else: # If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())


def Section_Detail(request,section): #Show detial of section
	if "role" in request.session: #Check role in session
		course = Course.objects.get(Section_ID=section)
		section_list = Section.objects.get(Section_ID=course)
		return render_to_response('SectionDetial.html',locals())
	else: # If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def Student_List(request,section): #Show detial student in section
	if "role" in request.session: #Check role in session
		course = Course.objects.get(Section_ID=section)
		student_list = Student.objects.filter(Section_ID=course)
		LabID = calculate_TotalLab(student_list)
		MidtermID = calculate_TotalMidterm(student_list)
		FinalID = calculate_TotalFinal(student_list)
		return render_to_response('StudentList.html',locals())
	else: # If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def calculate_TotalLab(student_list): #Calculate score Lab
	LabID = []
	Lab_list = []
	k = 0
	for i in student_list:
		Lab_list.append(Lab.objects.get(Lab_ID=i.Lab_ID)) #keep LabID
		LabID.append([])
		LabID[k].append(i.Lab_ID) #keep LabID
		LabID[k].append(Lab_list[k].Score_Lab1 + Lab_list[k].Score_Lab2 + Lab_list[k].Score_Lab3 + Lab_list[k].Score_Lab4) #calculate score total Lab
		k = k+1
	return LabID


def calculate_TotalMidterm(student_list): #Calculate score midterm
	MidtermID = []
	Midterm_list = []
	k = 0
	for i in student_list:
		Midterm_list.append(Midterm.objects.get(Midterm_ID=i.Midterm_ID)) #keep MidtermID
		MidtermID.append([])
		MidtermID[k].append(i.Midterm_ID) #keep MidtermID
		 #calculate score total Midterm
		MidtermID[k].append(Midterm_list[k].Score_Midterm1 + Midterm_list[k].Score_Midterm2 + Midterm_list[k].Score_Midterm3 + Midterm_list[k].Score_Midterm4)

		k = k+1
	return MidtermID

def calculate_TotalFinal(student_list): #calculate score final
	FinalID = []
	Final_list = []
	k = 0
	for i in student_list:
		Final_list.append(Final.objects.get(Final_ID=i.Final_ID)) #keep FinalID
		FinalID.append([])
		FinalID[k].append(i.Final_ID)#keep FinalID
		 #calculate score total Final
		FinalID[k].append(Final_list[k].Score_Final1 + Final_list[k].Score_Final2 + Final_list[k].Score_Final3 + Final_list[k].Score_Final4)
		k = k+1
	return FinalID

def Lab_List(request,LabID): #Show detial score lab
	if "role" in request.session: #Check role in session
		Lab_list = Lab.objects.get(Lab_ID=LabID)# Get value of Lab object from Lab ID 	
		return render_to_response('LabList.html',locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def Midterm_List(request,MidtermID): #Show detial score midterm
	if "role" in request.session: #Check role in session
		Midterm_list = Midterm.objects.get(Midterm_ID=MidtermID) # Get value of Midterm object from Midterm ID 
		return render_to_response('MidtermList.html',locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def Final_List(request,FinalID): #Show detial score final
	if "role" in request.session: #Check role in session
		Final_list = Final.objects.get(Final_ID=FinalID)
		return render_to_response('FinalList.html',locals()) # Get value of Final object from Final ID 
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def ShowForm_AddScore(request): #Show page form add score
	if "role" in request.session: #Check role in session
		temp = 'addscore'
		form = ContactForm()
		return render_to_response('addform.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())


@csrf_exempt
def Save_Student(request): #Save data of Student
	if request.POST['temp'] == 'addscore': #Save data for Add Score
		# Get value from form Add Score
		if( (not request.POST['sID']) or(not request.POST['sName']) or (not request.POST['sLastname']) or (not request.POST['secID']) or(not request.POST['lab1']) or (not request.POST['lab2']) or (not request.POST['lab3']) or (not request.POST['lab4']) or (not request.POST['Midterm1'] ) or (not request.POST['Midterm2'] ) or (not request.POST['Midterm3'] ) or (not request.POST['Midterm4'] ) or (not request.POST['Final1'] ) or (not request.POST['Final2'] ) or (not request.POST['Final3'] ) or (not request.POST['Final4'] )):
			return HttpResponse("You must fill in all of the fields.")
		sID = request.POST['sID'] # set student ID 
		sName = request.POST['sName'] #set student name
		sLastname = request.POST['sLastname'] #set student lastname 
		secID = request.POST['secID']  #set section 
		lab1 = request.POST['lab1'] #set score lab1
		lab2 = request.POST['lab2'] #set score lab2
		lab3 = request.POST['lab3'] #set score lab3
		lab4 = request.POST['lab4'] #set score lab4
		Midterm1 = request.POST['Midterm1'] #set score Midterm1
		Midterm2 = request.POST['Midterm2'] #set score Midterm2
		Midterm3 = request.POST['Midterm3'] #set score Midterm3
		Midterm4 = request.POST['Midterm4'] #set score Midterm4
		Final1 = request.POST['Final1'] #set score Final1
		Final2 = request.POST['Final2'] #set score Final2
		Final3 = request.POST['Final3'] #set score Final3
		Final4 = request.POST['Final4'] #set score Final4
		# call function Add_Score for sava data student into database
		temp = Add_Score(sID,sName,sLastname,secID,lab1,lab2,lab3,lab4,Midterm1,Midterm2,Midterm3,Midterm4,Final1,Final2,Final3,Final4)
	else: # Save data for Edit Score
		sid = request.POST['x'] #get value of id for Edit data
		# save new data in old data
		student_id = Student.objects.get(id=sid)
		user = User.objects.get(username = student_id.Student_ID)
		Lab_list = Lab.objects.get(Lab_ID=student_id.Lab_ID)
		Mid_list = Midterm.objects.get(Midterm_ID=student_id.Midterm_ID)
		Final_list = Final.objects.get(Final_ID=student_id.Final_ID)
		if request.POST['sID'] != student_id.Student_ID :
			if Student.objects.filter(Student_ID = request.POST['sID']):
				return HttpResponse("Student ID repeate")
		student_id.Student_ID = request.POST['sID'] #set student ID 
		student_id.Student_Name = request.POST['sName'] #set student name
		student_id.Student_Lastname = request.POST['sLastname'] #set student lastname 
		Lab_list.Score_Lab1 = request.POST['lab1'] #set score lab1
		Lab_list.Score_Lab2 = request.POST['lab2'] #set score lab2
		Lab_list.Score_Lab3 = request.POST['lab3'] #set score lab3
		Lab_list.Score_Lab4 = request.POST['lab4'] #set score lab4
		Mid_list.Score_Midterm1 = request.POST['Midterm1'] #set score Midterm1
		Mid_list.Score_Midterm2 = request.POST['Midterm2'] #set score Midterm2
		Mid_list.Score_Midterm3 = request.POST['Midterm3'] #set score Midterm3
		Mid_list.Score_Midterm4 = request.POST['Midterm4'] #set score Midterm4
		Final_list.Score_Final1 = request.POST['Final1'] #set score Final1
		Final_list.Score_Final2 = request.POST['Final2'] #set score Final2
		Final_list.Score_Final3 = request.POST['Final3'] #set score Final3
		Final_list.Score_Final4 = request.POST['Final4'] #set score Final4
		student_id.Total_Score = int(request.POST['lab1'])+int(request.POST['lab2'])+int(request.POST['lab3'])+int(request.POST['lab4'])+int(request.POST['Midterm1'])+int(request.POST['Midterm2'])+int(request.POST['Midterm3'])+int(request.POST['Midterm4'])+int(request.POST['Final1'])+int(request.POST['Final2'])+int(request.POST['Final3'])+int(request.POST['Final4']) #save total score
		course = Course.objects.get(Section_ID = request.POST['secID'])
		sec = Section.objects.get(Section_ID = course)
		student_id.Section_ID = sec #save section 
		student_id.save() #save data student into database 
		Lab_list.save() #save data lab into database 
		Mid_list.save() #save data midterm into database 
		Final_list.save() #save data final into database 
		user.username = request.POST['sID'] #save username
		user.save() #save data user into database 
		status = "success"
		temp = "Edit Score Success."
		return render_to_response('changePassSuccess.html', locals())
	return HttpResponse(str(temp))

def Random_ID():
	import random
	ids = random.randrange(10000,99999)
	if not Student.objects.filter(Lab_ID = ids):
		ID = ids
		return ID
	else :
		Random_ID()
	
#Save data for Add score
def Add_Score(sID,sName,sLastname,secID,lab1,lab2,lab3,lab4,Midterm1,Midterm2,Midterm3,Midterm4,Final1,Final2,Final3,Final4):
	student_list = Student.objects.all()
	if not Student.objects.filter(Student_ID=sID): #Check Sudent ID not repeate
		try:
			Course.objects.get(Section_ID=secID)
		except:
			return render_to_response('error.html', locals())
		total_student = len(Student.objects.filter(Section_ID = secID))+1 #calculate total student
		ids = Random_ID()
		course = Course.objects.get(Section_ID = secID)
		sec = Section.objects.get(Section_ID = course)
		sec.Amount_Student = total_student #save amount of student into database
		sec.save() #save data section into database
		total_score = int(lab1)+int(lab2)+int(lab3)+int(lab4)+int(Midterm1)+int(Midterm2)+int(Midterm3)+int(Midterm4)+int(Final1)+int(Final2)+int(Final3)+int(Final4) #calculate total score
		student = Student(Student_ID=sID,Student_Name=sName,Student_Lastname=sLastname,Section_ID=sec,Lab_ID=ids,Midterm_ID=ids,Final_ID=ids,Total_Score=total_score)
		student.save() #save data student into database
		Calculate_Grade(student) #call function Calculate_Grade
		lab = Lab(Lab_ID=student,Score_Lab1 =lab1 ,Score_Lab2 =lab2 ,Score_Lab3 = lab3,Score_Lab4 =lab4 )
		lab.save() #save data Lab into database
		midterm = Midterm(Midterm_ID=student ,Score_Midterm1 =Midterm1 ,Score_Midterm2 =Midterm2 ,Score_Midterm3 = Midterm3,Score_Midterm4 =Midterm4 )
		midterm.save() #save data midterm into database
		final = Final(Final_ID=student ,Score_Final1 =Final1 ,Score_Final2 =Final2 ,Score_Final3 = Final3,Score_Final4 =Final4 )
		final.save() #save data final into database
		try:
			User.objects.get(username = sID) #filter username in User
		except: # if filter error
			user = User(username = sID,password = '123456',role = 'student')
			user.save() # save username , password and role into database
		status = "success"
		temp = "Add Score Success."
		return render_to_response('changePassSuccess.html', locals())
	else : #if student ID repeate
		status = "success"
		temp = "Data Duplicate"
		return render_to_response('changePassSuccess.html', locals())

def ShowForm_EditScore(request): #Show page edit score for select section
	if "role" in request.session: #Check role in session
		section_list = Section.objects.all()
		return render_to_response('editform.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def EditScore_Section(request,secID): #Show student in section for edit score
	if "role" in request.session: #Check role in session
		section_list = Section.objects.all()
		course = Course.objects.get(Section_ID=secID)
		student_list = Student.objects.filter(Section_ID=course)
		LabID = calculate_TotalLab(student_list) #call function calculate_TotalLab
		MidtermID = calculate_TotalMidterm(student_list) #call function calculate_TotalMidterm
		FinalID = calculate_TotalFinal(student_list) #call function calculate_TotalFinal
		return render_to_response('editstudentlist.html',locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def Edit_Score(request,sid): #Show form edit score
	if "role" in request.session: #Check role in session
		temp = 'editscore'
		student_list = Student.objects.get(Student_ID=sid)
		Lab_list = Lab.objects.get(Lab_ID=student_list.Lab_ID)
		Mid_list = Midterm.objects.get(Midterm_ID=student_list.Midterm_ID)
		Final_list = Final.objects.get(Final_ID=student_list.Final_ID)
		form = ContactForm()
	 	form = ContactForm(initial={'sID': student_list.Student_ID,'sName': student_list.Student_Name,'sLastname': student_list.Student_Lastname,'secID': student_list.Section_ID,'lab1': Lab_list.Score_Lab1,'lab2': Lab_list.Score_Lab2,'lab3': Lab_list.Score_Lab3,'lab4': Lab_list.Score_Lab4,'Midterm1': Mid_list.Score_Midterm1,'Midterm2': Mid_list.Score_Midterm2,'Midterm3': Mid_list.Score_Midterm3,'Midterm4': Mid_list.Score_Midterm4,'Final1': Final_list.Score_Final1,'Final2': Final_list.Score_Final2,'Final3': Final_list.Score_Final3,'Final4': Final_list.Score_Final4})
		return render_to_response('addform.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def ShowForm_AddCourse(request): #Show form add course
	if "role" in request.session: #Check role in session
		temp = 'addcourse' #set temp = addcourse
		form = ContactFormCourse()
		return render_to_response('addcourseform.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

@csrf_exempt
def Save_Course(request): #Save data of course
	if request.POST['temp'] == 'addcourse': # Save data for Add Course
		SubjectID = request.POST['SubjectID'] #set Subject ID
		SubjectName = request.POST['SubjectName'] #set Subject Name
		SectionID = request.POST['SectionID'] #set Section ID
		ListTA = request.POST['ListTA'] #Set TA
		ListTeacher = request.POST['ListTeacher'] #set teacher
		result = AddCourse(SubjectID,SubjectName,SectionID,ListTA,ListTeacher) #call function AddCourse
	else: # Save data for Edit Course
		courseid = request.POST['x'] #get value of id for Edit data
		# save new data in old data
		course = Course.objects.get(id=courseid)
		section = Section.objects.get(Section_ID=course)
		course.Subject_ID = request.POST['SubjectID']  #set Subject ID
		course.Subject_Name = request.POST['SubjectName']  #set Subject Name
		course.Section_ID = request.POST['SectionID']  #set Section ID
		course.save() #save course data into database
		section.Section_ID = course #set section
		section.List_TA = request.POST['ListTA'] #set TA
		section.List_Teacher = request.POST['ListTeacher'] #set teacher
		section.save()  #save section data into database
		if not User.objects.filter(username = request.POST['ListTA']):
			user = User(username = request.POST['ListTA'],password='123456',role='student')
			user.save()
		if not User.objects.filter(username = request.POST['ListTeacher']):
			user = User(username = request.POST['ListTeacher'],password='123456',role='Teacher')
			user.save()

		return HttpResponse("OK")
	return HttpResponse(str(result))

def AddCourse(SubjectID,SubjectName,SectionID,ListTA,ListTeacher): # Save data course into database
	if not Course.objects.filter(Section_ID = SectionID): #Check Section ID not repeate
		student = Student.objects.all()
		course = Course(Subject_ID=SubjectID,Subject_Name=SubjectName,Section_ID=SectionID)
		course.save() # Save data course into database
		section = Section(Section_ID=course,List_TA=ListTA,List_Teacher=ListTeacher,Amount_Student=0)
		if not User.objects.filter(username = ListTA):
			user = User(username = ListTA ,password = '123456' ,role = "student")
			user.save()
		if not User.objects.filter(username = ListTeacher):
			user = User(username = ListTeacher ,password = '123456' ,role = "Teacher")
			user.save()
		section.save() # Save data section into database
		status = "success"
		temp = "Add Course Success."
		return render_to_response('changePassSuccess.html', locals())
	else : #if data duplicate
		status = "success"
		temp = "Data Duplicate"
		return render_to_response('changePassSuccess.html', locals())



def Edit_Course(request,courseid): #Show page form edit course
	if "role" in request.session: #Check role in session
		temp = 'editcourse' #set temp = editcourse
		course = Course.objects.get(id = courseid)
		section = Section.objects.get(Section_ID=course)
	 	form = ContactFormCourse(initial={'SubjectID':course.Subject_ID,'SubjectName':course.Subject_Name,'SectionID':course.Section_ID,'ListTA':section.List_TA,'ListTeacher':section.List_Teacher})
		return render_to_response('addcourseform.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def Calculate_Grade_All(): #Calculate grade all student
	student_list = Student.objects.all()
	for i in student_list :
		Calculate_Grade(i) #call function Calculate_Grade

def Calculate_Grade(student): #Calculate grade each one student
	if student.Total_Score < 50 :
		student.grade = 'F'
	elif student.Total_Score >= 50 and student.Total_Score < 55 :
		student.grade = 'D'  
	elif student.Total_Score >= 55 and student.Total_Score < 60 :
		student.grade = 'D+'
	elif student.Total_Score >= 60 and student.Total_Score < 65 :
		student.grade = 'C'
	elif student.Total_Score >= 65 and student.Total_Score < 70 :
		student.grade = 'C+'
	elif student.Total_Score >= 70 and student.Total_Score < 75 :
		student.grade = 'B'
	elif student.Total_Score >= 75 and student.Total_Score < 80 :
		student.grade = 'B+'
	elif student.Total_Score >= 80 and student.Total_Score <= 100 : 	
		student.grade = 'A'
	student.save() #Save grade into database
	
def ShowForm_GradeSec(request): #Show page form choose section for show grade
	if "role" in request.session: #Check role in session
		section_list = Section.objects.all()
		return render_to_response('showscoreForm.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def Show_GradeSec(request,secID): #Show grade each section
	if "role" in request.session: #Check role in session
		course = Course.objects.get(Section_ID = secID)
		sec = Section.objects.get(Section_ID = course)
		student = Student.objects.filter(Section_ID = sec)
		LabID = calculate_TotalLab(student)
		MidtermID = calculate_TotalMidterm(student)
		FinalID = calculate_TotalFinal(student)
		return render_to_response('ShowGradeSec.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def Show_GradeAllSec(request): #Show Grade All Section
	if "role" in request.session: #Check role in session
		student = Student.objects.all()
		LabID = calculate_TotalLab(student) #call function calculate_TotalLab
		MidtermID = calculate_TotalMidterm(student) #call function calculate_TotalMidterm
		FinalID = calculate_TotalFinal(student) #call function calculate_TotalFinal
		return render_to_response('ShowGradeSecAll.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

def ShowGrade_StudentID(request,SID): #Show Grade for 1 student
	if "role" in request.session: #Check role in session
		role = request.session["role"] #get role in session
		if (role == "student") or (role == "Student") or (role == "STUDENT"): #check role for student
			student = Student.objects.get(Student_ID = SID)
			lab = Lab.objects.get(Lab_ID = student.Lab_ID)
			midterm = Midterm.objects.get(Midterm_ID = student.Midterm_ID)
			final = Final.objects.get(Final_ID = student.Final_ID)
			return render_to_response('ShowGradeStudent_ID.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())
	
def ShowForm_login(request): #Show form Login
	request.session.clear() # clear session
	form = ContactFormLogin()	
	return render_to_response('Form_Login.html', locals())

@csrf_exempt
def Show_List(request):
	if "role" in request.session: #Check role in session
		role = request.session["role"] #get role in session
		if (role == "student") or (role == "Student") or (role == "STUDENT"):#check role for student
			userID = request.session['userID'] #get username in session
			if not "Sec" in request.session:
				TA_Sec = request.session["TA_Sec"] #get TA section in session
				return render_to_response('Select_TA.html',locals())
			Sec = request.session["Sec"] #get section in session
			student = Student.objects.get(Student_ID = userID)
			if Section.objects.filter(List_TA = student.Student_ID): #check student is TA 
				TA_Sec = request.session["TA_Sec"] #get TA section in session
				return render_to_response('Select_Ta.html',locals())
			else: # if student is not TA
				return render_to_response('Select_Student.html',locals())				
		elif (role == "Admin") or (role == "admin") or (role == "ADMIN"): #check role for ADMIN
			return render_to_response('Select_Admin.html',locals())
		elif (role == "teacher") or (role == "Teacher") or (role == "TEACHER"): #check role for TEACHER
			Teacher_Sec = request.session["Teacher_Sec"] #get Teacher section in session
			return render_to_response('Select_Teacher.html',locals())
					
	else:
		if "Username" in request.POST:
			form = ContactFormLogin()
			if (not request.POST['Username']) or (not request.POST['passwords']): #if don't have Add username or password 
				status = "error" 
				error = "Please enter your username or password" #show message
				return render_to_response('Form_Login.html', locals())
			else: #have Add username or password 
				user_id = request.POST['Username'] 
				user_pass = request.POST['passwords']
				try: #filter username in User
					user_list = User.objects.get(username = user_id)
				except:# if filter error
					status = "error"
					error = "The username or password you entered is incorrect. Please try again (make sure your caps lock is off)"
					return render_to_response('Form_Login.html', locals())
				request.session["userID"] = user_id #set username into session
				userID = request.session['userID'] #get username in session
				request.session["userPass"] = user_pass #set password into session
				if user_list.password == user_pass: #if Add password equal password in database
					if (user_list.role == "student") or (user_list.role == "Student") or (user_list.role == "STUDENT"):#check role for student
						try:
							student = Student.objects.get(Student_ID = user_id)
						except:
							if Section.objects.filter(List_TA = userID):
								section = Section.objects.filter(List_TA = userID)
								request.session["TA_Sec"] = section #set TA section into session
								TA_Sec = request.session["TA_Sec"] #get TA section in session
								request.session["role"] = user_list.role 
								return render_to_response('Select_TA.html', locals())		
						request.session["Sec"] = student.Section_ID #set section into session
						Sec = request.session["Sec"]#get section in session
						request.session["role"] = user_list.role #set role into session
						if Section.objects.filter(List_TA = student.Student_ID): #if student is TA
							section = Section.objects.filter(List_TA = student.Student_ID)
							request.session["TA_Sec"] = section #set TA section into session
							TA_Sec = request.session["TA_Sec"] #get TA section in session
							return render_to_response('Select_Ta.html', locals())
						else:#if student is not TA
							return render_to_response('Select_Student.html', locals())

					elif (user_list.role == "Admin") or (user_list.role == "admin") or (user_list.role == "ADMIN") :#check role for admin
						request.session["role"] = user_list.role #set role into session
						return render_to_response('Select_Admin.html', locals())
					elif (user_list.role == "teacher") or (user_list.role == "Teacher") or (user_list.role == "TEACHER"):#check role for teacher
						request.session["role"] = user_list.role #set role into session
						if Section.objects.filter(List_Teacher = userID): #check database have teacher in course					
							section = Section.objects.filter(List_Teacher = userID)
							request.session["Teacher_Sec"] = section #set teacher section into session
							Teacher_Sec = request.session["Teacher_Sec"] #get teacher section in session
							return render_to_response('Select_Teacher.html', locals())
						else: #if don't have teacher in course, return Add Course
							return HttpResponse("Add Course")
					else : #if have role ,please contact Admin
						return HttpResponse("Please contact Admin")
				else : #if add username or password is incorrect
					status = "error"
					error = "The username or password you entered is incorrect. Please try again (make sure your caps lock is off)."
					return render_to_response('Form_Login.html', locals())
		else:# If it don't have role, It show login page. 
			form = ContactFormLogin()
			status = "error"
			error = "Please Login"
			return render_to_response('Form_Login.html', locals())

def View_Profile(request): #Show profile
	if "role" in request.session: #Check role in session
		role = request.session["role"]  #get role in session
		userID = request.session['userID'] #get username in session
		if (role == "student") or (role == "Student") or (role == "STUDENT"): #check role for student
			try:
				student = Student.objects.get(Student_ID = userID)
				user = User.objects.get(username = userID)
				return render_to_response('ViewProfileStudent.html', locals())
			except:
				user = User.objects.get(username = userID)
				return render_to_response('ViewProfileTA.html', locals())
		elif (role == "Teacher") or (role == "teacher") or (role == "TEACHER"): #check role for teacher
			user = User.objects.get(username = userID)
			return render_to_response('ViewProfileTeacher.html', locals())
		elif (role == "Admin") or (role == "admin") or (role == "Admin"): #check role for admin
			user = User.objects.get(username = userID)
			return render_to_response('ViewProfileAdmin.html', locals())
	else:# If it don't have role, It show login page. 
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

#  -----------------------Function From Jack -----------------------------

class scalx:
        def __init__(self,numberX,positionX,positionfeq,Grade,feqnum):
                self.numberX = numberX
                self.positionX = positionX
                self.feq = positionfeq
                self.Grade = Grade
                self.feqnum = feqnum 

class scaly:
        def __init__(self,numberY,positionY):
                self.numberY = numberY
                self.positionY = positionY

def ShowHistrogram_ScoreAllSec(request):
	if "role" in request.session: #Check role    
		feq = []
		feq1 = []
		amount = 0
		cal = 0
		scalX = 160 # position start for X
		scalY = 100 # position start for Y
		temp = 0
		feqa = 0
                
		amount = len(Student.objects.all())  # query max of student
		cal = (amount/13)+1  # calculate scale from max student

		for i in range(0,101):
			feq.append(len(Student.objects.filter(Total_Score = i)))  # fine frequency all object student (0-100)
			if feq[i] == 0:
                                feq1.append("")
                        else:
                                feq1.append(str(feq[i]))

		number_scalX = []
		number_scalY = []
		
		for k in range(0,101): # scale for Graph X
			feqa = ((2210/(cal*13))*feq[100-k])+100 # calculate position of graph 
			number_scalX.append(scalx(100-k,scalX,feqa,"",feq1[100-k]))
			scalX = scalX + 50
	      
		for j in range(0,14): # scale for Graph X
                        number_scalY.append(scaly(temp*cal,scalY))
			scalY = scalY + 170
			temp = temp + 1
                
		return render_to_response('ShowScore.html',locals())
	else:
		return HttpResponse('Please Login')

def ShowHistrogram_ScoreSec(request,section):
        feq = []
        feq1 = []
	amount = 0
	cal = 0
	scalX = 160 # position start for X
	scalY = 100 # position start for Y
	temp = 0
	feqa = 0

        course =Course.objects.get(Section_ID = section)
        sec = Section.objects.get(Section_ID = course)
        
	amount = len(Student.objects.filter(Section_ID = sec))  # query max of student
	cal = (amount/13)+1  # calculate scale from max student

	for i in range(0,101):
		feq.append(len(Student.objects.filter(Section_ID = sec,Total_Score = i)))  # fine frequency all object student (0-100)
		if feq[i] == 0:
                        feq1.append("")
                else:
                        feq1.append(str(feq[i]))
	
	number_scalX = []
	number_scalY = []
		
	for k in range(0,101): # scale for Graph X
		feqa = ((2210/(cal*13))*feq[100-k])+100 # calculate position of graph 
		number_scalX.append(scalx(100-k,scalX,feqa,"",feq1[100-k]))
		scalX = scalX + 50
	      
	for j in range(0,14): # scale for Graph X
                number_scalY.append(scaly(temp*cal,scalY))
		scalY = scalY + 170
		temp = temp + 1
		
        return render_to_response('ShowScore.html',locals())

def HistorgramGradeAll(request):
	if "role" in request.session: #Check role
		feq = []
		amount = 0
		cal = 0
		scalX = 300 # position start for X
		scalY = 110 # position start for X  
		temp = 13
		feqa = 0
		Grade = ["A","B+","B","C+","C","D+","D","F"]
		
		amount = len(Student.objects.all())  # query max of student
		cal = (amount/13)+1  # calculate scale from max student

		for i in range(0,8):
			feq.append(len(Student.objects.filter(grade = Grade[i])))  # fine frequency all object student (0-100)
        
		number_scalX = []
                number_scalY = []
                
		for k in range(0,8): # scale for Graph X
			feqa = 1400-((1300/(cal*13))*feq[k]) # calculate position of graph
			number_scalX.append(scalx(k,scalX,feqa,Grade[k],0))
			scalX = scalX + 200

		for j in range(0,14): # scale for Graph Y
                        number_scalY.append(scaly(temp*cal,scalY))
			scalY = scalY + 100
			temp = temp - 1

		return render_to_response('ShowHistogramGrade.html',locals())
	else:
		return HttpResponse('Please Login')

def HistorgramGradeSec(request,section):
        feq = []
        amount = 0
        cal = 0
        scalX = 300 # position start for X
        scalY = 110 # position start for X      
        temp = 13
        feqa = 0
        Grade = ["A","B+","B","C+","C","D+","D","F"]

        course =Course.objects.get(Section_ID = section)
        sec = Section.objects.get(Section_ID = course)
        
        amount = len(Student.objects.filter(Section_ID = sec))  # query max of student
        cal = (amount/13)+1  # calculate scale from max student

        for i in range(0,8):
                feq.append(len(Student.objects.filter(Section_ID = sec,grade = Grade[i])))  # fine frequency all object student (0-100)
        
        number_scalX = []
        number_scalY = []
                
	for k in range(0,8): # scale for Graph X
		feqa = 1400-((1300/(cal*13))*feq[k]) # calculate position of graph
		number_scalX.append(scalx(k,scalX,feqa,Grade[k],0))
		scalX = scalX + 200

	for j in range(0,14): # scale for Graph Y
                number_scalY.append(scaly(temp*cal,scalY))
		scalY = scalY + 100
		temp = temp - 1

        return render_to_response('ShowHistogramGrade.html',locals())


#  ------------------------ Function From Koe&Joe ------------------------
# function for changePassword
def changePass(request):
	if "role" in request.session:    # check for role in database 
		userID = request.session['userID']      # keep userID value
		userValidate = User.objects.all()       # define User Objects
		form = ContactFormChangePassword()
		return render_to_response('changePassPage.html', locals())
	else:           # check if role isn't in database
		return HttpResponse("Please Login")

# function if change password success
@csrf_exempt
def changePassSuccess(request):
	if "role" in request.session:      # check for role in database 
		form = ContactFormChangePassword()
		userPass = request.session['userPass']  # keep userPass value for User Password
		userID = request.session['userID']      # keep userID value for User ID
		CurrentPassword = request.POST['CurrentPassword']   # keep CurrentPassword value for current Password
		NewPassword = request.POST['NewPassword']           # keep NewPassword value for New Password
		NewPassword2 = request.POST['NewPassword2'] # keep NewPassword2 for New Password Again

                # check if CurrentPassword is equal userPass
		if CurrentPassword == userPass:
			if NewPassword == NewPassword2:     # check if new password is equal new password Again
				user = User.objects.get(username = userID)
				user.password = NewPassword
				user.save()
				status = "success"
				temp = "Change Password Success."
				return render_to_response('changePassSuccess.html', locals())
			else:   # check if new password is not equal new password Again
				status = "error"
				error = "New Password Do not Match!"
				return render_to_response('changePassPage.html', locals())
		else:   # check if CurrentPassword is not equal userPass
			status = "error"
			error = "Currect Password Do not Match!"
			return render_to_response('changePassPage.html', locals())

	else:
		return HttpResponse("Please Login")
            

# function for call template register.html
def register(request):
	if "role" in request.session:
		role = request.session["role"]
		if (role == "Admin") or (role == "admin") or (role == "Admin"):
			return render_to_response('register.html', locals())
		else:
			form = ContactFormLogin()
			status = "error"
			error = "Please Login"
			return render_to_response('Form_Login.html', locals())
	else:
		form = ContactFormLogin()
		status = "error"
		error = "Please Login"
		return render_to_response('Form_Login.html', locals())

# function if register success
@csrf_exempt
def regis_success(request):
	if "role" in request.session:
		role = request.session["role"]
		userValidate = User.objects.all()
		uName = request.POST['userName']
		uRole = request.POST['select_role']
		if request.POST['userName'] and request.POST['select_role']:    # check input is getting
			if not User.objects.filter(username = request.POST['userName']): #Check data not repeate
                                # declare User Objects
				User_ob = User.objects.create(username = uName,password = "123456",role = uRole)
				return render_to_response('register_success.html', locals())
			else :          # check input isn't getting
				status = "error"
                                error = "Data duplicate! Please Register again."
                                return render_to_response('register.html', locals())
		else :          # chech if input isn't gettings
			status = "error"
			error = "Please enter your username or role"
			return render_to_response('register.html', locals())
	else:
		return HttpResponse("Please Login")

# function for call template upload.html
def upload(request):
    return render_to_response('upload.html')

# upload file keep it's in value
def handle_uploaded_file(f): 
    destination = open("temp/temp.txt", 'wb+')  # create file text
    for chunk in f.chunks():
        destination.write(chunk)    # write data
    destination.close()

# import file    
@csrf_exempt
def import_file(request):
	if request.method == 'POST': 
		handle_uploaded_file(request.FILES['n'])   # call function for create file 
		fo = open("temp/temp.txt", "r")    # open file for read
	
	    #while open(): 
		read_file = fo.read();        # read 
		arr = read_file.splitlines()  # split data in text file from line
		fo.close()
		countline = len(arr)  # count line in text file to use for calculate
	
		field = len(arr[2].split(','))
	
		a = 0   # define a = 0 for use to index
		arr2d = []
		x = [[arr2d for colum in range(field)] for row in range(countline-1)]  # create array 2D
		while a < (countline - 3) :
			b = 0
			while b < field :
				get_value = arr[a+3].split(',')  # line of score and name 
				x[a][b] = get_value[b]           # collect in array 2D
				b += 1
			a += 1
	    
	    # array for collect data    
		header    = []
		section     = []
		studentID   = []
		first_name  = []
		last_name   = []
		lab1 = []
		lab2 = []
		lab3 = []
		lab4 = []
		mid1 = []
		mid2 = []
		mid3 = []
		mid4 = []
		final1 = []
		final2 = []
		final3 = []
		final4 = []
		total = []
	
	    # loop for divide type of data
		i = 0
		while i < (countline - 3):
			j = 0
			while j < field :
				if j == 0 :
					section.append(x[i][j]) 
				elif j == 1 :
					studentID.append(x[i][j]) 
				elif j == 2 :
					first_name.append(x[i][j])        
				elif j == 3 :
					last_name.append(x[i][j])   
				elif j == 4 :
					lab1.append(x[i][j])
				elif j == 5 :
					lab2.append(x[i][j])
				elif j == 6 :
					lab3.append(x[i][j])  
				elif j == 7 :
					lab4.append(x[i][j])
				elif j == 8 :
					mid1.append(x[i][j]) 
				elif j == 9 :
					mid2.append(x[i][j])
				elif j == 10 :
					mid3.append(x[i][j]) 
				elif j == 11 :
					mid4.append(x[i][j]) 
				elif j == 12 :
					final1.append(x[i][j])   
				elif j == 13 :
					final2.append(x[i][j])
				elif j == 14 :
					final3.append(x[i][j])
				elif j == 15 :
					final4.append(x[i][j])
				j += 1
			i += 1
		header = arr[1].split(',') # for keep header file
		#return HttpResponse(arr[1])
	    # Find Total_Score
		i = 0
		while i < (countline - 3):
			total.append(int(lab1[i])+int(lab2[i])+int(lab3[i])+int(lab4[i])+int(mid1[i])+int(mid2[i])+int(mid3[i])+int(mid4[i])+int(final1[i])+int(final2[i])+int(final3[i])+int(final4[i]))
			i += 1
	    	          
	    
	    # check section  
		if not Course.objects.filter(Section_ID = section[0]):
	    	  # create Course
			Course_Ob = Course.objects.create(Subject_ID = header[0],
				Subject_Name = header[1],
				Section_ID = section[0])
		      # create Section
			Section_Ob = Section.objects.create(Section_ID = Course_Ob,
				List_TA = header[3],
				List_Teacher = header[2],
				Amount_Student = 0)
			if not User.objects.filter(username = header[2]):
				user = User(username = header[2],password = '123456',role = 'Teacher')
				user.save()
			if not User.objects.filter(username = header[3]):
				user = User(username = header[3],password = '123456',role = 'student')
				user.save()
		
		      # create objects about score
			count = 0
			i = 0
			while i < countline-3: # a number of student
				StudentList = Student.objects.all()
				temp = len(StudentList)+1
				count = count+1
				Student_Ob = Student.objects.create(Student_ID = studentID[i],
					Student_Name = first_name[i],
					Student_Lastname = last_name[i],
					Section_ID = Section_Ob,
					Lab_ID = temp,
					Midterm_ID = temp,
					Final_ID = temp,
					Total_Score = total[i])
				Lab_Ob = Lab.objects.create(Lab_ID = Student_Ob,
					Score_Lab1 = lab1[i],
					Score_Lab2 = lab2[i],
					Score_Lab3 = lab3[i],
					Score_Lab4 = lab4[i])
				Midterm_Ob = Midterm.objects.create(Midterm_ID = Student_Ob,
					Score_Midterm1 = mid1[i],
					Score_Midterm2 = mid2[i],
					Score_Midterm3 = mid3[i],
					Score_Midterm4 = mid4[i])
				Final_Ob = Final.objects.create(Final_ID = Student_Ob,
					Score_Final1 = final1[i],
					Score_Final2 = final2[i],
					Score_Final3 = final3[i],
					Score_Final4 = final4[i])
				if not User.objects.filter(username = studentID[i]):
					User_Ob = User.objects.create(username = studentID[i],
					password = "123456",
					role = "student")
				i += 1
				Section_Ob.Amount_Student = count  # a number of student
				Section_Ob.save()
				Calculate_Grade_All()
	    
		else:
			return render_to_response('upload_failed.html') # if section is same
		return render_to_response('upload_success.html')  # if new section  
	return render_to_response('upload.html')   # if method is not POST

